//
//  SetViewController.m
//  A_Project_DLS151129_SQ
//
//  Created by 151129-49宋强 on 16/1/22.
//  Copyright © 2016年 www.lanou3g.com蓝鸥. All rights reserved.
//

#import "SetViewController.h"
#import "UMSocialSinaHandler.h"
#import "UMSocial.h"
#import "Scan_VC.h"
#define Width self.view.frame.size.width
#define HEIGHT self.view.frame.size.height
@interface SetViewController ()
@property (nonatomic, assign) CGFloat memoryNum;
@end

@implementation SetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"设置";
    self.view.backgroundColor = [UIColor whiteColor];
        //初始化内存大小
    self.memoryNum = 0;
    [self numMemory];//计算缓存
    [self creatView];//创建View
    //设置夜间模式
    [self.view NightWithType:UIViewColorTypeNormal];
    [self.navigationController.navigationBar NightWithType:UIViewColorTypeNormal];
}
- (void)numMemory
{
    //创建管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //获取路径
    NSString *catchPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
    if ([fileManager fileExistsAtPath:catchPath]) {
        NSArray *files = [fileManager subpathsAtPath:catchPath];
        //遍历所有文件
        for (NSInteger i = 0; i < files.count; i++) {
            NSString *filePath = [catchPath stringByAppendingPathComponent:files[i]];
            //获取文件大小
            float k = [[fileManager attributesOfItemAtPath:filePath error:nil] fileSize];
            self.memoryNum += k;
        }
        
    }

}
- (void)creatView
{
    for (NSInteger i= 0; i < 5; i++) {
        UIView *setView = [[UIView alloc] initWithFrame:CGRectMake(0, i *80 + 5, Width, 80)];
        [setView NightWithType:UIViewColorTypeNormal];//夜间模式
        UILabel *dayLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, 100, 40)];
        [dayLabel NightWithType:UIViewColorTypeNormal];
        [setView addSubview:dayLabel];
        [dayLabel release];
        if (i == 0) {
            dayLabel.text = @"夜间模式";
            UISwitch *swc = [[UISwitch alloc] initWithFrame:CGRectMake(Width - 20 - 60, 20, 60, 40)];
            swc.tag = 6000;
            [swc addTarget:self action:@selector(swcAction:) forControlEvents:UIControlEventValueChanged];
            [setView addSubview:swc];
            [swc release];
        }else if (i == 1){
            dayLabel.text = @"本地推送";
            UISwitch *swc = [[UISwitch alloc] initWithFrame:CGRectMake(Width - 20 - 60, 20, 60, 40)];
            swc.tag = 8000;
            [swc addTarget:self action:@selector(swcAction:) forControlEvents:UIControlEventValueChanged];
            [setView addSubview:swc];
            [swc release];

        }else if (i == 2){
            dayLabel.text = @"清除缓存";
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
            [setView addGestureRecognizer:tap];
            [tap release];
            UILabel *huancunLabel = [[UILabel alloc] initWithFrame:CGRectMake(Width - 20 - 60, 20, 100, 40)];
            huancunLabel.tag = 1000;
#pragma mark - 显示缓存大小
            huancunLabel.text = [NSString stringWithFormat:@"%.2fM", self.memoryNum / 1024 / 1024];
            [setView addSubview:huancunLabel];
            [huancunLabel release];
        }else if(i == 3){
            dayLabel.text = @"扫一扫";
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(swipe:)];
            [setView addGestureRecognizer:tap];
            [tap release];
        }else{
            dayLabel.text = @"退出应用";
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapBreak:)];
            [setView addGestureRecognizer:tap];
            [tap release];
        }
        [self.view addSubview:setView];
        [setView release];
    }
}
#pragma mark -扫一扫
- (void)swipe:(UITapGestureRecognizer *)tap
{
    Scan_VC *VC = [[Scan_VC alloc] init];
    [self.navigationController pushViewController:VC animated:YES];
    [VC release];
}

#pragma mark - 手势触发方法 清除缓存
- (void)tapAction:(UITapGestureRecognizer *)tap
{
    NSFileManager *fManager = [NSFileManager defaultManager];
    NSString *catchPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
    [fManager removeItemAtPath:catchPath error:nil];//删除缓存
    UILabel *label = (UILabel *)[self.view viewWithTag:1000];
    label.text = @"0.00M";
    [self promptViewWithMessage:@"清除成功"];
    
}
- (void)promptViewWithMessage:(NSString *)message
{
    UIView *tishiView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 80, 40)];
    tishiView.center = self.view.center;
    tishiView.backgroundColor = [UIColor blackColor];
    tishiView.alpha = 0.5;
    tishiView.layer.cornerRadius = 10;
    [self.view addSubview:tishiView];
    [tishiView release];
    UILabel *tishilabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, 70, 30)];
    tishilabel.textColor = [UIColor whiteColor];
    tishilabel.text = message;
    [tishiView addSubview:tishilabel];
    [tishilabel release];
    //延时
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [tishiView removeFromSuperview];
    });

}
#pragma mark -退出登录
- (void)tapBreak:(UITapGestureRecognizer *)tap
{
    BOOL isLogin = [[NSUserDefaults standardUserDefaults] boolForKey:@"isLogin"];
    if (isLogin) {
        //如果已经登录则询问是否退出应用
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否退出登录" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *yesAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //删除本地信息
            NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"userInfo.plist"];
            NSDictionary *dic = [NSDictionary dictionary];
            [dic writeToFile:path atomically:YES];
            //登录状态设置为NO
            [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isLogin"];
            [self promptViewWithMessage:@"退出成功"];
        }];
        UIAlertAction *noAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:yesAction];
        [alert addAction:noAction];
        [self presentViewController:alert animated:yesAction completion:^{
            
        }];
        

    }else{
        [self promptViewWithMessage:@"没有登录"];
    }
}
#pragma mark - 视图将要出现时判断开关状态
- (void)viewWillAppear:(BOOL)animated
{
    UISwitch *swc = [self.view viewWithTag:6000];
    BOOL isNight = [[NSUserDefaults standardUserDefaults] boolForKey:@"night"];
    if (isNight) {
        swc.on = YES;
    }else{
        swc.on = NO;
    }
}
#pragma mark - 夜间模式和本地推送开关
- (void)swcAction:(UISwitch *)swc
{
    if (swc.tag == 6000) {
        [ThemeManage shareThemeManage].isNight = ![ThemeManage shareThemeManage].isNight;
        [[NSNotificationCenter defaultCenter] postNotificationName:@"changeColor" object:nil];
        [[NSUserDefaults standardUserDefaults] setBool:[ThemeManage shareThemeManage].isNight forKey:@"night"];
    }else{
        if (swc.isOn) {
            #pragma mark - 创建一个本地推送
            UILocalNotification *notification = [[[UILocalNotification alloc] init] autorelease];
            //设置2秒之后
            NSDate *pushDate = [NSDate dateWithTimeIntervalSinceNow:20];
            if (notification != nil) {
                //设置推送时间
                notification.fireDate = pushDate;
                //设置时区
                notification.timeZone = [NSTimeZone defaultTimeZone];
                //设置重复间隔
                notification.repeatInterval = kCFCalendarUnitDay;
                //推送声音
                notification.soundName = UILocalNotificationDefaultSoundName;
                //推送内容
                notification.alertBody = @"推送内容";
                //显示在icon上的红色圈子的数字
                notification.applicationIconBadgeNumber = 1;
                //设置userinfo 方便在之后需要撤销的时候使用
                NSDictionary *info = [NSDictionary dictionaryWithObject:@"name" forKey:@"key"];
                notification.userInfo = info;
                //ios8之后需要添加这个注册,才能得到授权
                if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
                    UIUserNotificationType type = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge |UIUserNotificationTypeSound;
                    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type categories:nil];
                    [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
                }
                //添加推送到UIApplication
                UIApplication *app = [UIApplication sharedApplication];
                [app scheduleLocalNotification:notification];
            }
        }else{
            #pragma mark -解除本地推送
            //获得 UIApplication
            UIApplication *app = [UIApplication sharedApplication];
            //获取本地推送数组
            NSArray *localArray = [app scheduledLocalNotifications];
            //声明本地通知对象
            UILocalNotification *localNotification = nil;
            if (localArray) {
                for (UILocalNotification *noti in localArray) {
                    NSDictionary *dict = noti.userInfo;
                    if (dict) {
                        NSString *inkey = [dict objectForKey:@"key"];
                        if ([inkey isEqualToString:@"name"]) {
                            if (localNotification) {
                                [localNotification release];
                                localNotification = nil;
                            }
                            localNotification = [noti retain];
                            break;
                        }
                    }
                }
                //判断是否找到已经存在的相同key的推送
                if (!localNotification) {
                    //不存在初始化
                    localNotification = [[UILocalNotification alloc] init];
                }
                if (localNotification) {
                    //不推送 取消推送
                    [app cancelLocalNotification:localNotification];
                    [localNotification release];
                    return;
                }
            }

        }
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
